package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.mapper.TravelContentMapper;
import cn.wolfcode.luowowo.article.mapper.TravelMapper;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.ITravelService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {
    @Autowired
    private TravelMapper travelMapper;
    @Autowired
    private TravelContentMapper travelContentMapper;

    public PageInfo query(TravelQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        return new PageInfo(travelMapper.selectForList(qo));
    }

    public Travel get(Long id) {
        Travel travel = travelMapper.selectByPrimaryKey(id);
        TravelContent travelContent = travelContentMapper.selectByPrimaryKey(id);
        travel.setTravelContent(travelContent);
        return travel;
    }

    public List<Travel> getViewnumTop3TravelsByDestId(Long destId) {
        return travelMapper.selectViewnumTop3TravelsByDestId(destId);
    }

    public Long saveOrUpdate(Travel travel) {
        //lastUpdateTime,最新更新时间
        travel.setLastUpdateTime(new Date());
        //summary,摘要
        TravelContent travelContent = travel.getTravelContent();
        String content = travelContent.getContent();
        if(content.length() >= 200){
            travel.setSummary(content.substring(0,200));
        }else {
            travel.setSummary(content);
        }
        if(travel.getId() == null){
            //createTime,创建时间
            travel.setCreateTime(new Date());
            travelMapper.insert(travel);
            //travelContent，游记内容
            travelContent.setId(travel.getId());
            travelContentMapper.insert(travelContent);
        }else {
            travelMapper.updateByPrimaryKey(travel);
            //travelContent，游记内容
            travelContent.setId(travel.getId());
            travelContentMapper.update(travel.getId(),content);
        }
        return travel.getId();
    }

    public List<Travel> list() {
        return travelMapper.selectAll();
    }

    public void updateState(Long id, int state) {
        travelMapper.updateState(id,state);
    }

    @Override
    public List<Travel> getTop3ByUserId(Long uid) {
        return travelMapper.selectTop3ByUserId(uid);
    }

    @Override
    public List<Travel> getByUserId(Long id) {
        return travelMapper.selectByUserId(id);
    }


}
